package com.ciwong.epaper.modules.epaper.ui;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.adapter.BookOrServiceAdapter;
import com.ciwong.epaper.modules.epaper.adapter.HotWordAdapter;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.Grade;
import com.ciwong.epaper.modules.epaper.bean.NewBook;
import com.ciwong.epaper.modules.epaper.bean.SearchBookKeyNameBean;
import com.ciwong.epaper.modules.epaper.bean.Subject;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.widget.GradeSelectDialog;
import com.ciwong.epaper.widget.ItemSubjectType;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.epaper.widget.RecycleViewDivider;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by albus on 2017/4/6.
 */

public class ShopSearchBookActivity extends BaseActivity implements PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemClickListener {

	public RecyclerView recyclerView;
	private BookOrServiceAdapter mBookOrServiceAdapter;
//	public SwipeToLoadLayout swipeToLoadLayout;
	private PullToRefreshView pullToRefreshView;

	/**
	 * 搜索关键字
	 */
	private EditText edt_searching_book_str;
	protected boolean isRefesh = true;
	private int mPageIndex = 1;
	protected boolean isEmpty = false;
	private ItemSubjectType item_subject_type;
	private TextView btn_grade_condition;
	private int mGradeId;
	private int mSubjectId;
	private LinearLayout ll_hot_word;
	private RelativeLayout rel_search_empty;
	private LinearLayout ll_grade_subject_condition;
//    private String areaId;
	/**
	 * 热门搜索词语
	 */
	private ListView lv_hot_word;
	private HotWordAdapter hotWordAdapter;
	private List<SearchBookKeyNameBean> searchBookKeyNameBeanList = new ArrayList<SearchBookKeyNameBean>();
	private int mTotalCount = 0;

	@Override
	protected int setView() {
		return R.layout.activity_shop_searchbook;
	}

	@Override
	protected void findViews() {

		ll_hot_word = (LinearLayout) findViewById(R.id.ll_hot_word);
		lv_hot_word = (ListView) findViewById(R.id.lv_hot_word);
		ll_grade_subject_condition = (LinearLayout) findViewById(R.id.ll_grade_subject_condition);
		rel_search_empty = (RelativeLayout) findViewById(R.id.rel_search_empty);
		recyclerView = (RecyclerView) findViewById(R.id.swipe_target);
//		swipeToLoadLayout = (SwipeToLoadLayout) findViewById(R.id.swipeToLoadLayout);
		pullToRefreshView = (PullToRefreshView) findViewById(R.id.ptr_shop_search);

		item_subject_type = (ItemSubjectType) findViewById(R.id.item_subject_type);
		btn_grade_condition = (TextView) findViewById(R.id.btn_grade_condition);
		edt_searching_book_str = (EditText) findViewById(R.id.edt_searching_book_str);
		edt_searching_book_str.setSingleLine();

	}

	@Override
	protected void initEvent() {

//		swipeToLoadLayout.setOnRefreshListener(this);
//		swipeToLoadLayout.setOnLoadMoreListener(this);
		pullToRefreshView.setOnHeaderRefreshListener(this);
		pullToRefreshView.setOnFooterRefreshListener(this);

		findViewById(R.id.btn_select_grade).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				GradeSelectDialog gradeSelectDialog = new GradeSelectDialog(ShopSearchBookActivity.this, new GradeSelectDialog.OnGradeSelectListener() {
					@Override
					public void onGradeSelect(int gradeId, String gradeName) {
						btn_grade_condition.setText(gradeName);
						mGradeId = gradeId;
						mSubjectId = 0;
						mPageIndex = 1;
						mTotalCount=0;
						isRefesh = true;
						Clazz clazz = EApplication.getInstance().getClazz();
						int schoolId = 0;
						String areaId = "0";
						if (clazz != null) {
							areaId = clazz.getSchoolArea();
							schoolId = clazz.getSchoolID();
						}
						item_subject_type.setGradeId(gradeId, null, 2, areaId, schoolId, 0);
						String mKeyWords = null;

						getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
						Grade grade = new Grade();
						grade.setGradeId(mGradeId);
						grade.setGradeName(gradeName);
						EApplication.getInstance().setGrade(grade);

//                        loadDataFromNet();
					}
				});
				gradeSelectDialog.show();

			}
		});

		item_subject_type.setOnSubjectSelectListener(new ItemSubjectType.OnSubjectSelectListener() {
			@Override
			public void onSubjectSelect(int position, Subject subject) {

				mPageIndex = 1;
				mSubjectId = subject.getSubjectId();
				isRefesh = true;
				getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
			}
		});

		findViewById(R.id.iv_clear_keywords).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				edt_searching_book_str.setText("");
			}
		});


	}


	/**
	 * 监听键盘，如果是回车，就开始搜索书本
	 *
	 * @param event
	 * @return
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		String putKeyWords = edt_searching_book_str.getText().toString().trim();
		CWLog.d(TAG, "putkeywods#####indispatch#####" + putKeyWords);
		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
			/*隐藏软键盘*/
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (inputMethodManager.isActive()) {
				inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			}
			mPageIndex = 1;
			isRefesh = true;
			//输入的不为“”（空字符串）
			if (!TextUtils.isEmpty(putKeyWords)) {
				getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
			}
//            if (!isSearching) {//防止监听键盘时搜索两次
//                isSearching = true;
//                curPage = 1;
//                loadDataFromNet();
//            }

			return true;
		}
		return super.dispatchKeyEvent(event);
	}


	@Override
	protected void loadData() {

//        getListDataFormNet(mPageIndex,mGradeId,mSubjectId,mKeyWords);
		hotWordAdapter = new HotWordAdapter(searchBookKeyNameBeanList);
		lv_hot_word.setAdapter(hotWordAdapter);
		lv_hot_word.setOnItemClickListener(this);

		loadHotWord();

	}

	@Override
	protected void init() {

		setTitleText("搜索");
		TAG = "searchTag";
		setBackImg(R.mipmap.nav_btn_return_down);

		btn_grade_condition.setText(EApplication.getInstance().getGrade().getGradeName());
		mGradeId = EApplication.getInstance().getGrade().getGradeId();
		Clazz clazz = EApplication.getInstance().getClazz();
		int schoolId = 0;
		String areaId = "0";
		if (clazz != null) {
			areaId = clazz.getSchoolArea();
			schoolId = clazz.getSchoolID();
		}
		item_subject_type.setGradeId(mGradeId, null, 2, areaId, schoolId, 0);

		mBookOrServiceAdapter = new BookOrServiceAdapter();
		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		recyclerView.setAdapter(mBookOrServiceAdapter);
//		swipeToLoadLayout.setOnRefreshListener(this);
//		swipeToLoadLayout.setOnLoadMoreListener(this);
		pullToRefreshView.setOnHeaderRefreshListener(this);
		pullToRefreshView.setOnFooterRefreshListener(this);
		recyclerView.addItemDecoration(new RecycleViewDivider(ShopSearchBookActivity.this,
				LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.light_gray15)));

	}


//	@Override
//	public void onLoadMore() {
//		isRefesh = false;
//		getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
//	}
//
//	@Override
//	public void onRefresh() {
//		isRefesh = true;
//		mPageIndex = 1;
//		getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
//	}
	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		isRefesh = false;
		getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		isRefesh = true;
		mPageIndex = 1;
		getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
	}

	private void loadHotWord() {
		if (!NetworkUtils.isOnline()) {
			ToastUtil.INSTANCE.toastCenterNoNetError();
			//			swipeToLoadLayout.setRefreshing(false);
			pullToRefreshView.onHeaderRefreshComplete();
		} else {
			SchoolDetail schoolDetail = EApplication.getInstance().getSchoolDetail();
			try {
				int schoolId = 0;
				if (null != schoolDetail) {
					schoolId = schoolDetail.getSchoolId();
				}

				EpaperRequest.getBookKey(EApplication.BRAND_ID + "", schoolId + "",
						new BaseExtCallBack(ShopSearchBookActivity.this) {
							@Override
							public void success(Object data) {
								super.success(data);

								if (data != null) {
									List<SearchBookKeyNameBean> searchBookKeyNameBean = (List<SearchBookKeyNameBean>) data;
									CWLog.d(TAG, "getbookkey英语，数学" + searchBookKeyNameBean.size());
									if (searchBookKeyNameBean.size() > 0) {
										searchBookKeyNameBeanList.addAll(searchBookKeyNameBean);
										showHotWordView();
										hotWordAdapter.notifyDataSetChanged();
									}
								} /*else {
							showNormalView();
						}*/

							}

							@Override
							public void failed(int errorCode, Object data) {
								super.failed(errorCode,data);
								CWLog.d(TAG, "shopERRORCODE####" + errorCode);
								ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(R.string.connect_server_error,errorCode);
								showEmptyView();
							}

							@Override
							public void failed(Object data) {
								super.failed(data);
								ToastUtil.INSTANCE.toastCenterError(R.string.connect_server_error);

							}
						});

			} catch (Exception e) {

			}
		}
	}


	private void getListDataFormNet(int pageIndex, int gradeId, int subjectId) {
		if (NetworkUtils.isOnline()) {
			String putKeyWords = null;
			if (null != edt_searching_book_str.getText()) {
				putKeyWords = edt_searching_book_str.getText().toString().trim();
			}
			showNormalView();
			String myKeyWords = URLEncoder.encode(putKeyWords);

			CWLog.d(TAG, "################最终的myKeyWords######" + myKeyWords);


			Clazz clazz = EApplication.getInstance().getClazz();
			String areaId = "0";
			if (clazz != null) {
				areaId = clazz.getSchoolArea();
			}

			EpaperDao.getInstance().getBookOrServiceList(EApplication.BRAND_ID, pageIndex, 10,
					0, gradeId, subjectId, 2, areaId, myKeyWords,
					new BaseExtCallBack(ShopSearchBookActivity.this) {

						@Override
						public void failed(int errorCode, Object data) {
							super.failed(errorCode, data);
							if (errorCode != 17 & errorCode != 27 & errorCode != 10004) {
								showEmptyView();
								pullToRefreshView.onHeaderRefreshComplete();
								pullToRefreshView.onFooterRefreshComplete();
								ToastUtil.INSTANCE.toastCenterError(R.string.connect_server_error);
							}
						}

						@Override
						public void failed(Object data) {
							super.failed(data);
							showEmptyView();
							pullToRefreshView.onHeaderRefreshComplete();
							pullToRefreshView.onFooterRefreshComplete();
							ToastUtil.INSTANCE.toastCenterError(R.string.connect_server_error);

						}

						@Override
						public void success(Object data) {


//                        ll_no_net_page.setVisibility(View.GONE);
//                        swipeToLoadLayout.setVisibility(View.VISIBLE);

							BasePaging<NewBook> basePaging = (BasePaging<NewBook>) data;
							List<NewBook> netList = null;
							if (null != basePaging) {
								netList = basePaging.getPageList();
								mTotalCount = basePaging.getTotalCount();
							}
//							swipeToLoadLayout.setRefreshing(false);
//							swipeToLoadLayout.setLoadingMore(false);
							pullToRefreshView.onHeaderRefreshComplete();
							pullToRefreshView.onFooterRefreshComplete();

							if (isRefesh) {
								if (null != netList && netList.size() > 0) {
									isEmpty = false;
									mPageIndex++;
								} else {
									//数目为0
//                                netList = new ArrayList<>();
									isEmpty = true;
								}
//
//                            mEpaperInfoList=netList;
//                            mBookCaseAdapter.setDataList(mEpaperInfoList);
								mBookOrServiceAdapter.setDataList(netList);

							} else {
								if (null != netList && netList.size() > 0) {
									isEmpty = false;
									mBookOrServiceAdapter.addDataList(netList);
//                                mEpaperInfoList.addAll(netList);
//                                mBookCaseAdapter.setDataList(mEpaperInfoList);
									mPageIndex++;
								} else {
									pullToRefreshView.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
								}
							}
							//总量相等说明数据已经全部加在完毕
							if(mTotalCount==mBookOrServiceAdapter.getDataList().size()){
								pullToRefreshView.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
							}else{
								pullToRefreshView.setFooterState(PullToRefreshView.PULL_TO_REFRESH);
							}

							if (isEmpty) {
								showEmptyView();
							} else {
								showNormalView();
							}
							hideMiddleProgressBar();
						}

					});
		} else {
			ToastUtil.INSTANCE.toastCenterNoNetError();
			//			swipeToLoadLayout.setRefreshing(false);
//			swipeToLoadLayout.setLoadingMore(false);
			pullToRefreshView.onHeaderRefreshComplete();
			pullToRefreshView.onFooterRefreshComplete();
		}
	}


	public void showHotWordView() {
		ll_hot_word.setVisibility(View.VISIBLE);
		rel_search_empty.setVisibility(View.GONE);
		ll_grade_subject_condition.setVisibility(View.GONE);

		recyclerView.setVisibility(View.INVISIBLE);
	}

	public void showNormalView() {

		ll_hot_word.setVisibility(View.GONE);
		ll_grade_subject_condition.setVisibility(View.VISIBLE);
		rel_search_empty.setVisibility(View.GONE);
		recyclerView.setVisibility(View.VISIBLE);
	}

	public void showEmptyView() {
		ll_hot_word.setVisibility(View.GONE);
		ll_grade_subject_condition.setVisibility(View.VISIBLE);
		rel_search_empty.setVisibility(View.VISIBLE);

		recyclerView.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position < searchBookKeyNameBeanList.size()) {
			String hotWord = searchBookKeyNameBeanList.get(position).keyName;
			edt_searching_book_str.setText(hotWord);
			getListDataFormNet(mPageIndex, mGradeId, mSubjectId);
		}

	}


}
